//
//  MainPlusTabBar.swift
//  sinaweiboFirst
//
//  Created by mac on 16/3/6.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class MainPlusTabBar: UITabBar {
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(plusBtn)
    }

    //从xib/sb中加载视图控件会调用这个方法
    //swift中 实现了默认的构造函数 编译器只认为支持手写代码 如果从xib加载 崩溃
    required init?(coder aDecoder: NSCoder) {
        //默认致命错误 可以注销默认错误代码 让当前控件支持从xib/sb中加载
        fatalError("init(coder:) has not been implemented")
//        super.init(coder:aDecoder)
    }

    //添加子视图  子视图的frame发生变化 
    //不建议在layoutSubviews中添加子视图
    override func layoutSubviews() {
        
        super.layoutSubviews()

        let w = UIScreen.mainScreen().bounds.width / 5
        let h = self.bounds.height
        
        let rect = CGRect(x: 0, y: 0, width: w, height: h)
        
        //increase index
        var index: CGFloat = 0
        
        for subview in subviews {
            
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                //修改subview的frame x,y值改变
                subview.frame = CGRectOffset(rect, index * w, 0)
                
//                if index == 1 {
//                    index++
//                }
//                index++
                index +=  (index == 1) ? 2 : 1
            }
        }
        
        //添加子视图
//        addSubview(plusBtn)
        //frame
        plusBtn.frame = CGRectOffset(rect, 2 * w, 0)
        
//        //这样写会添加两个按钮
//        let btns = addbtn()
//        addSubview(btns)
//        btns.frame = CGRectOffset(rect, 2 * w, 0)

    }
    
    //闭包懒加载子视图
    lazy var plusBtn: UIButton = UIFactory.buttonWithImage("tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
//    private func addbtn() -> UIButton {
//    
//        let btn = UIButton()
//        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
//        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Selected)
//        
//        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
//        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Selected)
//        
//        btn.sizeToFit()
//        return btn
//    }
   

}
